/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Input, Avatar, Form, Empty, Spin, Radio } from 'antd';
import styles from './index.less';
import { connect } from 'dva';
import { names } from '../../config';
import KbChildrenWrapper from '@/components/KbChildrenWrapper';
import KbModal from '@/components/KbModal';
import KbIcon from '@/components/KbIcon';
import { isArray } from 'lodash';

const { Item: FormItem } = Form;
const { Group: RadioGroup, Button: RadioButton } = Radio;

@Form.create()
@connect(({ loading, source }) => ({
  list: source.kopBrand,
  getting: loading.effects['source/getKopBrand'],
  authing: loading.effects['source/auth'],
}))
class Kop extends Component {
  static defaultProps = {
    onAdded: () => {},
  };
  constructor(props) {
    super(props);
    this.state = {
      visible_account: false,
      visible_list: false,
      brandIndex: 0,
      activeBrandIndex: 0,
    };
    this.inputKeys = {
      '2': {
        keys: ['customer_id', 'pwd'],
        icons: ['user', 'lock'],
      },
      '3': {
        keys: ['name', 'customer_id', 'pwd'],
        icons: ['number', 'user', 'lock'],
      },
    };
    this.tips = {
      yd: [
        '请与大客户账号经办人确认在运单网点后台，已将你的账号订单来源标记为“系统对接”，否则将无法生成三段码',
      ],
      // sto118: ['申通代收货款订单必须使用代收货款专用面单'],
      // sto588: ['申通到付订单必须使用到付专用面单'],
      // sto44: [
      //   '普通订单可用44/77面单；',
      //   '申通生鲜订单可用77626面单，且必须使用申通生鲜专用的绿色面单',
      // ],
      other: ['请确认输入信息正确，避免因错误信息不能正常打单'],
    };
  }

  // 获取快递员公司列表
  getList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'source/getKopBrand',
    });
  };

  //   打开或关闭指定弹窗
  onTriggerModal = (key, open, brandIndex) => {
    const { form } = this.props
    const state = {};
    const keys = isArray(key) ? key : [key];
    keys.map(key_ => {
      state[`visible_${key_}`] = open;
    });
    this.setState(
      {
        ...state,
      },
      () => {
        if (open) {
          if (key === 'list') {
            this.getList();
          } else if (key === 'account') {
            this.setState({
              brandIndex,
              activeBrandIndex: 0,
            });
          }
        }else{
          form.resetFields()
        }
      }
    );
  };

  // 切换当前激活的面单类型
  onChangeActive = e => {
    const { value: activeBrandIndex } = e.target;
    this.setState({
      activeBrandIndex,
    });
  };

  // 提交授权
  onOk = () => {
    const { form, dispatch, onAdded } = this.props;
    form.validateFields((err, values) => {
      if (err) return;
      const { list } = this.props;
      const { brandIndex, activeBrandIndex } = this.state;
      const { brand } = list[brandIndex].list[activeBrandIndex];
      dispatch({
        type: 'source/auth',
        payload: {
          brand,
          ...values,
        },
        kind: 'kop',
      }).then((res) => {
        if (res.code == 0) {
          this.onTriggerModal(['account', 'list'], false);
          form.resetFields();
          onAdded();
          dispatch({
            type: 'source/getAllSource',
          });
          //单号源设置页面，获取最新的下拉框数据
          dispatch({
            type:"setter/getOperatorOrderSourceList"
          })
        }
      });
    });
  };

  render() {
    const { visible_list, visible_account, brandIndex, activeBrandIndex } = this.state;
    const { children, getting, list, form, authing } = this.props;
    const title = names.kop.label;
    const currentBrandData = list[brandIndex];
    const { list: currentBrandList = [], brand } = currentBrandData || {};
    const activeBrandData = currentBrandList[activeBrandIndex] || {};
    const footerTips = this.tips[activeBrandData.brand || brand] || this.tips.other;
    return (
      <>
        <KbChildrenWrapper
          className="pointer"
          onClick={this.onTriggerModal.bind(this, 'list', true)}
        >
          {children}
        </KbChildrenWrapper>
        <KbModal
          width={600}
          visible={visible_account}
          onOk={this.onOk}
          onCancel={this.onTriggerModal.bind(this, 'account', false)}
          title={title}
          okButtonProps={{ loading: authing }}
          footer={
            <div className="kb-tips">
              <div className="kb-tips_title">提示</div>
              {footerTips.map((item, index) => (
                <div key={index} className="kb-tips_item">
                  {item}
                </div>
              ))}
            </div>
          }
        >
          {currentBrandData && (
            <div>
              <div className={styles.title}>
                <Avatar size="large" src={`//img.kuaidihelp.com/brand_logo/icon_${brand}.png`} />
                <div>{activeBrandData.brand_name}</div>
              </div>
              <Form className={styles.form}>
                {activeBrandData.input_text.map((item, index) => {
                  const { keys, icons } = this.inputKeys[`${activeBrandData.input}`];
                  const key = keys[index];
                  const icon = icons[index];
                  return (
                    <FormItem help="" key={key}>
                      {form.getFieldDecorator(key, {
                        rules: [
                          {
                            required: true,
                            message: item,
                          },
                        ],
                      })(
                        <Input
                          size="large"
                          prefix={icon != "number" && <KbIcon type={icon} style={{ color: '#999' }} />}
                          placeholder={item}
                        />
                      )}
                    </FormItem>
                  );
                })}
                {currentBrandList.length > 1 && (
                  <FormItem>
                    {/* <RadioGroup
                      onChange={this.onChangeActive}
                      value={activeBrandIndex}
                      className="kb-radio-group"
                    >
                      {currentBrandList.map((item, index) => (
                        <RadioButton key={item.brand} value={index}>
                          {item.brand_name}
                        </RadioButton>
                      ))}
                    </RadioGroup> */}
                  </FormItem>
                )}
              </Form>
            </div>
          )}
        </KbModal>
        <KbModal
          width={600}
          visible={visible_list}
          onCancel={this.onTriggerModal.bind(this, 'list', false)}
          title={title}
          okText=""
        >
          <div>
            <Spin spinning={!!getting}>
              {list && list.length ? (
                <div className={styles.list}>
                  {list.map((item, index) => (
                    <span
                      key={item.brand}
                      onClick={this.onTriggerModal.bind(this, 'account', true, index)}
                    >
                      <Avatar
                        size="large"
                        src={`//img.kuaidihelp.com/brand_logo/icon_${item.brand}.png`}
                      />
                      <span>{item.brand_name}</span>
                    </span>
                  ))}
                </div>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </Spin>
          </div>
        </KbModal>
      </>
    );
  }
}

export default Kop;
